#include <../include/middleWare/MiddlewareChain.hpp>
#include <muduo/base/Logging.h>
using namespace http::middleWare;

void MiddlewareChain::addMiddleware(std::shared_ptr<Middleware> middleware)
{
    middlewares.push_back(middleware);
}

void MiddlewareChain::processBefore(const HttpRequest& request)
{
    for (auto& middleware : middlewares)
    {
        middleware->before(request);
    }
}

void MiddlewareChain::processAfter(HttpResponse& response)
{
    try
    {
        //反向遍历 因为中间件是按顺序执行的，所以需要反向遍历 洋葱模型
        for (auto it = middlewares.rbegin(); it != middlewares.rend(); ++it)
        {
            (*it)->after(response);
        }
    }
    catch (const std::exception& e)
    {
        LOG_ERROR << "Error in MiddlewareChain::processAfter: " << e.what();
    }
}
